package com.daixin.blog.controller;

import com.daixin.blog.dto.CommentCreateDTO;
import com.daixin.blog.dto.CommentDTO;
import com.daixin.blog.dto.ResultDTO;
import com.daixin.blog.exception.CustomizeErrorCode;
import com.daixin.blog.menu.CommentTypeEnum;
import com.daixin.blog.model.Comment;
import com.daixin.blog.model.User;
import com.daixin.blog.service.CommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Author daixin
 */
@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;

    @ResponseBody
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    public Object post(@RequestBody CommentCreateDTO commentCreateDTO,
                       HttpServletRequest request) {
        User user =(User) request.getSession().getAttribute("user");//获得登陆状态
        if(user ==null){
            return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
        }
        if(commentCreateDTO==null|| StringUtils.isBlank(commentCreateDTO.getContent())){
            return ResultDTO.errorOf(CustomizeErrorCode.CONTENT_IS_EMPTY);
        }
            Comment comment = new Comment();
            comment.setParentId(commentCreateDTO.getParentId());
            comment.setContent(commentCreateDTO.getContent());
            comment.setType(commentCreateDTO.getType());
            comment.setGmtCreat(System.currentTimeMillis());
            comment.setGmtModified(System.currentTimeMillis());
            comment.setCommentator(user.getId());
            comment.setCommentCount(0);
            comment.setLikeCount(1L);
            commentService.insert(comment);
            return ResultDTO.okOf();
    }
    @ResponseBody
    @RequestMapping(value = "/comment/{id}",method = RequestMethod.GET)
    public ResultDTO<List<CommentDTO>> commets(@PathVariable(name = "id") Long id){
        List<CommentDTO> commentDTOS = commentService.listByTargetid(id, CommentTypeEnum.COMMENT);
        return ResultDTO.okOf(commentDTOS);
    }
}
